import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:ost_flutter_module/class/entity/store/store_home_banner_entity.dart';
import 'package:ost_flutter_module/class/entity/store/store_map_entity.dart';
import 'package:ost_flutter_module/class/entity/store/store_search_entity.dart';
import 'package:ost_flutter_module/network/base_request_model.dart';
import 'package:ost_flutter_module/network/completable_action.dart';
import 'package:ost_flutter_module/network/http_manager.dart';
import 'package:ost_flutter_module/network/url_constants.dart';
import 'package:ost_flutter_module/widget/loading/loading_view.dart';
import 'package:uuid/uuid.dart';

import '../../../../main.dart';

part 'course_page_event.dart';
part 'course_page_state.dart';

class CoursePageBloc extends Bloc<CoursePageEvent, CoursePageState> {
  CoursePageBloc() : super(CoursePageInitial());

  BaseRequestListModel<StoreHomeBannerEntity> _banner =
      BaseRequestListModel<StoreHomeBannerEntity>();
  BaseRequestListModel<StoreHomeBannerEntity> get banner => _banner;

  BaseRequestListModel<StoreMapEntity> _map =
      BaseRequestListModel<StoreMapEntity>();
  BaseRequestListModel<StoreMapEntity> get map => _map;

  BaseRequestListModel<StoreSearchEntityShiftList> _dataModel =
      BaseRequestListModel<StoreSearchEntityShiftList>();
  BaseRequestListModel<StoreSearchEntityShiftList> get dataModel => _dataModel;

  @override
  Stream<CoursePageState> mapEventToState(
    CoursePageEvent event,
  ) async* {
    if (event is CoursePageFetchDataInitial) {
      yield* _mapFetchData(event);
    } else if (event is CoursePageBanner) {
      yield* _mapFetchBanner(event);
    } else if (event is CoursePageMap) {
      yield* _mapFetchCourseMap(event);
    } else if (event is CoursePageFetchData) {
      yield* _mapFetchCourseData(event);
    }
  }

  _fetchBanner(CoursePageBanner event) async {
    var result =
        await HttpManager.getInstance().syncRequestList<StoreHomeBannerEntity>(
      '$store_course_banner/${event.code}',
      baseUrl: BASE_URL_MALL,
      method: Method.GET,
      params: null,
    );

    event?.action?.completer?.complete(true);

    if (result.isSuccess) {
      var list = result.getOrNull;
      _banner = _banner.copyWith(
        loadingStatus:
            (list.isEmpty) ? LoadingStatus.empty : LoadingStatus.success,
        dataList: list,
      );
    } else {
      _banner = _banner.copyWith(
        loadingStatus: LoadingStatus.error,
        dataList: null,
        isLastPage: false,
        errorMsg: result.exceptionOrNull?.showMsg,
      );
    }
  }

  _fetchMap(CoursePageMap event) async {
    var result =
        await HttpManager.getInstance().syncRequestList<StoreMapEntity>(
      store_course_map,
      baseUrl: BASE_URL_MALL,
      method: Method.GET,
      params: null,
    );

    event?.action?.completer?.complete(true);

    if (result.isSuccess) {
      var list = result.getOrNull;
      _map = _map.copyWith(
        loadingStatus:
            (list.isEmpty) ? LoadingStatus.empty : LoadingStatus.success,
        dataList: list,
      );
    } else {
      _map = _map.copyWith(
        loadingStatus: LoadingStatus.error,
        dataList: null,
        isLastPage: false,
        errorMsg: result.exceptionOrNull?.showMsg,
      );
    }
  }

  _fetchCourse(CoursePageFetchData event) async {
    var result =
        await HttpManager.getInstance().syncRequestList<StoreSearchEntityShiftList>(
      store_course_list,
      baseUrl: BASE_URL_MALL,
      params: {
        'campusId': event.campusId,
        'city': event.city,
        'code': event.code,
        'isonline': event.isonline,
        'tagId': event.tagId,
        'typeId': event.typeId,
      },
    );

    event?.action?.completer?.complete(true);

    if (result.isSuccess) {
      var list = result.getOrNull;
      _dataModel = _dataModel.copyWith(
        loadingStatus:
            (list.isEmpty) ? LoadingStatus.empty : LoadingStatus.success,
        dataList: list,
      );
    } else {
      _dataModel = _dataModel.copyWith(
        loadingStatus: LoadingStatus.error,
        dataList: null,
        isLastPage: false,
        errorMsg: result.exceptionOrNull?.showMsg,
      );
    }
  }

  Stream<CoursePageFetchSuccess> _mapFetchData(
    CoursePageFetchDataInitial event,
  ) async* {
    _fetchBanner(event.banner);
    _fetchMap(event.map);
    _fetchCourse(event.course);

    yield CoursePageFetchSuccess(Uuid().v4());
  }

  Stream<CoursePageBannerResult> _mapFetchBanner(
    CoursePageBanner event,
  ) async* {
    var result =
        await HttpManager.getInstance().syncRequestList<StoreHomeBannerEntity>(
      '$store_course_banner/${event.code}',
      baseUrl: BASE_URL_MALL,
      method: Method.GET,
      params: null,
    );

    event.action?.completer?.complete(true);

    if (result.isSuccess) {
      var list = result.getOrNull;
      // _dataModel = _dataModel.copyWith(
      //   loadingStatus:
      //       (list.isEmpty) ? LoadingStatus.empty : LoadingStatus.success,
      //   dataList: list,
      // );
      yield CoursePageBannerResult(Uuid().v4(), list: list);
    }
    //  else {
    //   logger.e(result.exceptionOrNull?.showMsg);
    //   _dataModel = _dataModel.copyWith(
    //     loadingStatus: LoadingStatus.error,
    //     dataList: null,
    //     isLastPage: false,
    //     errorMsg: result.exceptionOrNull?.showMsg,
    //   );
    // }
    yield CoursePageBannerResult(Uuid().v4(),
        errMsg: result.exceptionOrNull?.showMsg);
  }

  /// 全局字典数据
  Stream<CoursePageMapResult> _mapFetchCourseMap(
    CoursePageMap event,
  ) async* {
    var result =
        await HttpManager.getInstance().syncRequestList<StoreMapEntity>(
      store_course_map,
      baseUrl: BASE_URL_MALL,
      method: Method.GET,
      params: null,
    );

    event.action?.completer?.complete(true);

    if (result.isSuccess) {
      var list = result.getOrNull;
      // _dataModel = _dataModel.copyWith(
      //   loadingStatus:
      //       (list.isEmpty) ? LoadingStatus.empty : LoadingStatus.success,
      //   dataList: list,
      // );
      yield CoursePageMapResult(Uuid().v4(), list: list);
    }
    // else {
    // _dataModel = _dataModel.copyWith(
    //   loadingStatus: LoadingStatus.error,
    //   dataList: null,
    //   isLastPage: false,
    //   errorMsg: result.exceptionOrNull?.showMsg,
    // );
    // }

    yield CoursePageMapResult(Uuid().v4(),
        errMsg: result.exceptionOrNull?.showMsg);
  }

  /// 筛选课程
  Stream<CoursePageFetchSuccess> _mapFetchCourseData(
    CoursePageFetchData event,
  ) async* {
    var result =
        await HttpManager.getInstance().syncRequestList<StoreSearchEntityShiftList>(
      store_course_banner,
      baseUrl: BASE_URL_MALL,
      params: {
        'campusId': event.campusId,
        'city': event.city,
        'code': event.code,
        'isonline': event.isonline,
        'tagId': event.tagId,
        'typeId': event.typeId,
      },
    );

    logger.i(result);
    if (result.isSuccess) {
      var list = result.getOrNull;
      _dataModel = _dataModel.copyWith(
        loadingStatus:
            (list.isEmpty) ? LoadingStatus.empty : LoadingStatus.success,
        dataList: list,
      );
    } else {
      logger.e(result.exceptionOrNull?.showMsg);
      _dataModel = _dataModel.copyWith(
        loadingStatus: LoadingStatus.error,
        dataList: null,
        isLastPage: false,
        errorMsg: result.exceptionOrNull?.showMsg,
      );
    }

    event.action?.completer?.complete(true);
    yield CoursePageFetchSuccess(Uuid().v4());
  }
}
